<template>
  <div class="user-rights" v-loading="loading">
    <header class="header">
      <div class="left">
        <h2 class="title">{{ defaultNav ? defaultNav.label + '权限设置' : '成员权限设置' }}</h2>
        <ul class="nav-list" v-if="!defaultNav">
          <li
            class="nav-item"
            v-for="item in navList"
            :key="item.label"
            :class="{ active: item.component === currNav.component }"
            @click="changeNav(item)"
          >
            <span class="nav-text">{{ item.label }}</span>
          </li>
        </ul>

        <!-- 区域负责人的区域选择器 -->
        <div class="selector-container" v-if="isMultiSchool && currNav && currNav.level === 1">
          <el-cascader
            placeholder="选择地区"
            v-model="areaValue"
            :props="areaProps"
            clearable
            filterable
            class="cascader-selector"
          ></el-cascader>
        </div>

        <!-- 显示当前学校名称（非区域负责人） -->
        <span v-if="currNav && currNav.level !== 1" class="school-name">
          {{ schoolName }}
        </span>
      </div>
      <ButtonPermission code="rights:editTable" mode="disable">
        <template #default="{ disabled }">
          <el-button 
            type="primary" 
            size="small" 
            icon="el-icon-edit" 
            :disabled="disabled"
            @click="!disabled && toEditTable()" 
            v-show="currNav && currNav.level !== 1"
          >在线批量编辑</el-button>
        </template>
      </ButtonPermission>
    </header>
    <main class="view-wrapper">
      <MasterTable
        v-if="showTable"
        :masterDataList="masterDataList"
        :currNav="currNav"
        :schoolId="schoolId"
        @update="getList"
      />
    </main>

    <EditTableView
      v-if="showEditTable"
      :title="editTitle"
      :templatePath="templatePath"
      :sheetName="sheetName"
      :schoolId="schoolId"
      :tableDataList="tableDataList"
      :allUserList="allUserList"
      :noFirstColumn="level !== 3"
      @cancel="showEditTable = false"
      @update="onUpdateSuccess"
    />
  </div>
</template>
<script>
import MasterTable from './MasterTable.vue';
import EditTableView from '@/components/schoolmanage/EditTableView.vue';
import api from '@/api/api';
import { mapGetters, mapState } from 'vuex';

const navList = [
  { label: '区域负责人', component: 'AreaMaster', level: 1 },
  { label: '学校领导', component: 'SchoolMaster', level: 2 },
  { label: '年级科目负责人', component: 'SubjectMaster', level: 3 },
  { label: '考试管理员', component: 'ExamMaster', level: 4 },
];

const lazyLoad2 = async (node, resolve) => {
  const { level, value } = node;
  const areaId = level === 0 ? 0 : value;
  let list = [];
  switch (level) {
    case 0:
    case 1:
    case 2:
      const { F_districts } = await api.getDistricts2({
        F_parent_id: areaId,
      });
      list = F_districts.map(({ F_id, F_name }) => ({
        value: F_id,
        label: F_name,
        leaf: level === 2,
      }));
      break;
    default:
      break;
  }
  resolve(list);
};

const lazyLoad = async (node, resolve) => {
  const { level, value } = node;
  const areaId = level === 0 ? 0 : value;
  let list = [];
  switch (level) {
    case 0:
    case 1:
    case 2:
      const { F_districts } = await api.getDistricts2({
        F_parent_id: areaId,
      });
      list = F_districts.map(({ F_id, F_name }) => ({
        value: F_id,
        label: F_name,
        leaf: false,
      }));
      break;
    case 3:
      const { F_schools } = await api.getSchools({
        F_page: 0,
        F_area_id: areaId,
      });
      list = F_schools.map(({ F_id, F_name }) => ({
        value: F_id,
        label: F_name,
        leaf: true,
      }));
    default:
      break;
  }
  resolve(list);
};
export default {
  name: 'UserRights',
  components: {
    MasterTable,
    EditTableView,
  },
  props: {
    defaultNav: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      loading: true,
      navList: navList,
      currNav: {},
      userSchoolList: [],
      areaValue: [440000],
      schoolValue: [],
      areaProps: {
        lazy: true,
        checkStrictly: true,
        lazyLoad: lazyLoad2,
      },
      props: {
        lazy: true,
        lazyLoad,
      },
      masterDataList: [],
      dataList: [],
      columnList: [],
      showTable: true,

      // 批量编辑相关
      showEditTable: false,
      tableDataList: [],
      allUserList: [],
    };
  },
  computed: {
    ...mapGetters('user', ['userId', 'isSuperAdmin']),
    ...mapState('school', ['currentSchoolId']),
    isMultiSchool() {
      return this.userSchoolList.length > 1;
    },
    schoolId() {
      // 安全检查：确保 currNav 存在且有 level 属性
      if (!this.currNav || typeof this.currNav.level !== 'number') {
        return 0;
      }
      // 对于非区域负责人，使用Vuex中的当前学校ID
      if (this.currNav.level !== 1) {
        return this.currentSchoolId || 0;
      }
      // 区域负责人仍然使用schoolValue
      return this.schoolValue.length === 4 ? this.schoolValue.at(-1) : 0;
    },
    schoolName() {
      // 安全检查：确保 currNav 存在且有 level 属性
      if (!this.currNav || typeof this.currNav.level !== 'number') {
        return '';
      }
      // 对于非区域负责人，显示当前选中的学校名称
      if (this.currNav.level !== 1) {
        if (this.isMultiSchool) {
          const currentSchool = this.userSchoolList.find(school => school.F_id === this.schoolId);
          return currentSchool ? currentSchool.F_name : '';
        }
        // 单校模式，显示第一所学校名称
        return this.userSchoolList?.[0]?.F_name || '';
      }
      // 区域负责人不显示学校名称
      return '';
    },
    editTitle() {
      return '';
    },
    level() {
      // 安全检查：确保 currNav 存在且有 level 属性
      if (!this.currNav || typeof this.currNav.level !== 'number') {
        return 0;
      }
      return this.currNav.level;
    },
    templatePath() {
      const templatePathMap = {
        2: 'https://ebag-exam.oss-cn-shenzhen.aliyuncs.com/examination/teacher_sign/考务模版/阅卷系统单校版精准后台信息录入模板 (学校管理成员) .xlsx',
        3: 'https://ebag-exam.oss-cn-shenzhen.aliyuncs.com/examination/teacher_sign/考务模版/阅卷系统单校版精准后台信息录入模板 (年级科目负责人) .xlsx',
        4: 'https://ebag-exam.oss-cn-shenzhen.aliyuncs.com/examination/teacher_sign/考务模版/阅卷系统单校版精准后台信息录入模板 (考试管理成员) .xlsx',
      };
      return templatePathMap[this.level];
    },
    sheetName() {
      const sheetNameMap = {
        2: '学校管理成员',
        3: '年级科目负责人',
        4: '考试管理成员',
      };
      return sheetNameMap[this.level];
    },
  },
  watch: {
    areaValue() {
      this.getList();
    },
    currentSchoolId() {
      this.getList();
    },
    currNav() {
      this.getList();
    },
  },
  mounted() {
    if (!this.isSuperAdmin) {
      this.navList = navList.filter((item) => item.level !== 1);
    }
    
    // 如果有传入默认导航，则使用传入的导航
    if (this.defaultNav) {
      // 查找匹配的导航项
      const matchedNav = this.navList.find(item => item.component === this.defaultNav.component);
      if (matchedNav) {
        this.currNav = matchedNav;
      } else {
        this.currNav = this.navList[0];
      }
    } else {
      this.currNav = this.navList[0];
    }
    
    this.getUserSchoolList();
  },
  methods: {
    changeNav(item) {
      if (this.currNav.label === item.label) return;
      this.currNav = item;
    },
    async getUserSchoolList() {
      const { F_schools } = await this.$api.getUserSchoolList({
        F_user_id: this.userId,
        F_admin_id: this.userId,
        F_page: 1,
        F_limit: 10,
      });
      if (!F_schools || !F_schools.length) {
        this.loading = false;
        this.$toast('未查询到该账号下的学校列表');
        return;
      }
      this.userSchoolList = F_schools;
      this.loading = false;
      const {
        F_id,
        F_loc: { F_prov_id, F_city_id, F_district_id },
      } = F_schools[0];
      this.schoolValue = [F_prov_id, F_city_id, F_district_id, F_id];
    },
    async getList() {
      // 安全检查：确保 currNav 存在且有 level 属性
      if (!this.currNav || typeof this.currNav.level !== 'number') {
        return;
      }
      // 对于非区域负责人，需要确保有学校ID
      if (this.currNav.level !== 1 && !this.schoolId) {
        return;
      }
      // 对于区域负责人，需要确保有区域选择
      if (this.currNav.level === 1 && this.areaValue.length < 3) {
        return;
      }
      
      this.loading = true;
      const { level } = this.currNav;
      // 后端要求~
      const api =
        level === 3
          ? this.$api.getSchoolMasterList2
          : this.$api.getSchoolMasterList;

      let params = {};
      if (level === 1) {
        // 区域负责人的参数
        const [F_province_id, F_city_id, F_district_id] = this.areaValue;
        params = {
          F_province_id,
          F_city_id,
          F_district_id,
        };
      } else {
        // 另外3种成员的参数
        params = {
          F_school_id: this.schoolId,
        };
      }
      const { F_data } = await api({
        ...params,
        F_level: this.currNav.level,
      });
      this.masterDataList = F_data || [];
      this.showTable = false;
      this.$nextTick(() => {
        this.showTable = true;
        this.loading = false;
      });
    },

    async getAllUserList() {
      const { F_data } = await this.$api.getSchoolUserList({
        F_school_id: this.schoolId,
      });
      this.allUserList = (F_data || []).map(({ Id, Name }) => ({
        id: Id,
        name: Name,
      }));
    },
    async toEditTable() {
      if (!this.schoolId) {
        this.$toast('请先选择学校');
        return;
      }
      this.loading = true;
      await this.getAllUserList();
      this.loading = false;

      if (this.level === 3) {
        this.tableDataList = this.masterDataList.map(
          ({ GradeId, GradeName, SubUserList }) => ({
            id: GradeId,
            name: GradeName,
            sub_list: SubUserList.map(
              ({ SubjectId, SubjectName, UserList }) => ({
                sub_id: SubjectId,
                sub_name: SubjectName,
                user_list: (UserList || []).map(({ UserId, UserName }) => ({
                  user_id: UserId,
                  user_name: UserName,
                })),
              })
            ),
          })
        );
      } else {
        this.tableDataList = this.masterDataList.map(
          ({ RoleId, RoleName, UserList }) => ({
            id: RoleId,
            name: RoleName,
            user_list: UserList.map(({ UserId, UserName }) => ({
              user_id: UserId,
              user_name: UserName,
            })),
          })
        );
      }
      this.showEditTable = true;
    },
    onUpdateSuccess() {
      this.showEditTable = false;
      this.getList();
    },
  },
};
</script>
<style lang="less" scoped>
.user-rights {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #ebeef5;

    .left {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      
      .title {
        margin: 0 24px 0 0;
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }

      .nav-list {
        display: flex;
        margin: 0;
        padding: 0;
        list-style: none;

        .nav-item {
          padding: 0 16px;
          margin-right: 8px;
          font-size: 14px;
          height: 32px;
          line-height: 32px;
          color: #606266;
          cursor: pointer;
          border-radius: 16px;
          transition: all 0.3s;
          
          &:hover {
            color: #409eff;
            background-color: rgba(64, 158, 255, 0.08);
          }
          
          &.active {
            color: #fff;
            background-color: #409eff;
          }
        }
      }
      
      .selector-container {
        margin-left: 16px;
        
        .cascader-selector {
          width: 220px;
        }
      }
      
      .school-name {
        margin-left: 16px;
        font-weight: 500;
        color: #606266;
      }
    }
  }

  .view-wrapper {
    flex: 1;
    overflow: hidden;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  }
}
</style>
